<?php

/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/16
 * Time: 17:17
 * @copyright: ©2024 永州微聚商网络科技有限公司
 * @link: https://www.weijuyunke.com
 */

namespace app\admin\controller;

use app\admin\model\Role;
use app\admin\model\Staff;
use app\admin\model\StaffRole;
use app\home\model\AmountLog;
use app\home\model\GoodsOrder;
use app\home\model\PackageOrder;
use app\home\model\UserToken;
use app\merchant\model\PackageUseLog;
use app\merchant\model\Printer;
use app\Request;
use app\merchant\model\Store as StoreModel;
use app\services\jwt\JwtService;
use dh2y\qrcode\QRcode;
class Store
{
    /**
     * 添加商铺
     */
    public function addStore(Request $request)
    {
        $param = $request->param();
        $storeModel = new StoreModel();
        try {
            validate(\app\merchant\validate\Store::class)->check($param);
            $data = [
                'real_name' => $param['real_name'],
                'name' => $param['name'],
                'phone' => $param['phone'],
                'province_id' => $param['province_id'],
                'city_id' => $param['city_id'],
                'county_id' => $param['county_id'],
                'province_name' => $param['province_name'],
                'city_name' => $param['city_name'],
                'county_name' => $param['county_name'],
                'address' => $param['address'],
                'create_time' => time(),
                'logo' => $param['logo'],
                'account' => $param['account'],
                'longitude' => $param['longitude'],
                'dimension' =>  $param['dimension'],
                'navigation' =>  $param['navigation'],
            ];

            $storeModel->startTrans();
            $storeModel->insert($data);
            $storeId = $storeModel->getLastInsID();
            /**
                $QRcode = new QRcode();
             $url = getProtocol() . $_SERVER["HTTP_HOST"].'/pages/storePaymentCode/storePaymentCode?store_id='.$storeId;
            $imageString = $QRcode->png($url, './uploads/store/'.$storeId.'.png', "2", 4, 1)->entry();
            $storeModel->where(['id' => $storeId])->update(['qr_code' => $imageString]);
             */

            $staffAccount = new Staff();
            $staffAccountInfo = $staffAccount->where(['phone' => $param['phone']])->find();
            if ($staffAccountInfo) {
                $staffId = $staffAccountInfo['id'];
            } else {
                $salt = createNonceStr(4);
                $accountData = [
                    'phone' => $param['phone'],
                    'name' => $param['account'],
                    'password' => md5(md5($param['password']) . $salt),
                    'salt' => $salt,
                    'create_time' => time(),
                    'type' => 2,
                    /*  'pid' => $request->staff_account['id'],*/
                    'real_name' => $param['real_name'],
                ];
                $staffAccount->insert($accountData);
                $staffId = $staffAccount->getLastInsID();
            }
            $staffRole = new StaffRole();
            $staffRole->insert([  // 账号和权限关联
                'role_id' => $param['role_id'],
                'staff_id' => $staffId,
                'create_time' => time(),
                'store_id' => $storeId,
            ]);

            $storeModel->commit();
        } catch (\Exception $exception) {
            $storeModel->rollback();
            return adminError($exception->getMessage());
        }
        return success('添加成功');
    }
    public function editStore(Request $request)
    {
        $param = $request->param();
        $storeModel = new StoreModel();
        try {
            validate(\app\merchant\validate\Store::class)->check($param);
            $data = [
                'real_name' => $param['real_name'],
                'name' => $param['name'],
                'phone' => $param['phone'],
                'province_id' => $param['province_id'],
                'city_id' => $param['city_id'],
                'county_id' => $param['county_id'],
                'province_name' => $param['province_name'],
                'city_name' => $param['city_name'],
                'county_name' => $param['county_name'],
                'address' => $param['address'],
                'create_time' => time(),
                'logo' => $param['logo'],
                'account' => $param['account'],
                'longitude' => $param['longitude'],
                'dimension' =>  $param['dimension'],
                'navigation' =>  $param['navigation'],
            ];
            $storeModel->where(['id' => $param['id']])->update($data);

        } catch (\Exception $exception) {
            $storeModel->rollback();
            return adminError($exception->getMessage());
        }
        return success('添加成功');
    }
    public function upStoreStatus(Request $request)
    {
        $param = $request->param();
        $storeModel = new StoreModel();
        $storeModel->where(['id' => $param['id']])->update(['status' => $param['status']]);
        return success('操作成功');
    }

    public function  storeInfo(Request $request){
        $param = $request->param();
        $storeModel = new StoreModel();
        $storeInfo = $storeModel->where(['id' => $param['id']])->find();
        $QRcode = new QRcode();
        $url = getProtocol() . $_SERVER["HTTP_HOST"].'/H5/index.html?store_id='.$storeInfo['id'].'#/pages/storePaymentCode/storePaymentCode';
        $imageString = $QRcode->png($url, './uploads/store/'.$storeInfo['id'].'.png', "2", 4, 1)->entry();
        $storeInfo['qr_code']  =$imageString;
        return adminSuccess('店铺详情',$storeInfo);


    }

    public function storeRole()
    {
        $role = new Role();
        $data = $role ->where('type','>',1 ) ->where(['status' => 1])->select();

        return success('商户角色', $data);
    }

    /**
     * 查看账号角色
     */
    public function roleByPhone(Request $request)
    {
        $param = $request->param();
        $staffAccount = new Staff();
        $staffInfo = $staffAccount->where('phone', $param['account'])
            ->whereOr('name', $param['account'])
            ->find();
        if (empty($staffInfo)) {
            return adminError('账号不存在');
        }
        if ($staffInfo['type'] == 1) {
            return success('后台管理账号');
        }
        $staffRole = new StaffRole();// 账号门店
        $staffRoleData = $staffRole->where(['staff_id' => $staffInfo['id']])->select()->toArray();
        if (empty($staffRoleData)) {
            return adminError('账号未绑定门店');
        }
        $staffRoleIds = array_column($staffRoleData, 'role_id');
        $staffStoreIds = array_column($staffRoleData, 'store_id');
        $roleModel = new Role();
        $roleArray = $roleModel->where('id', 'in', $staffRoleIds)->select()->toArray();
        $roleArrayById = array_column($roleArray, null, 'id');
        $storeModel = new StoreModel();
        $storeArray = $storeModel->where('id', 'in', $staffStoreIds)->select()->toArray();
        $storeArrayById = array_column($storeArray, null, 'id');
        foreach ($staffRoleData as $key => $value) {
            $staffRoleData[$key]['store_name'] = $storeArrayById[$value['store_id']]['name'];
            $staffRoleData[$key]['role_name'] = $roleArrayById[$value['role_id']]['name'];
        }
        return success('账号角色', ['list' => $staffRoleData, 'count' => count($staffRoleData)]);
    }



    /**
     * 门店列表
     */
    public function storeList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }

        $where[] = ['status', 'in', [1,2]];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }
        $storeModel = new StoreModel();
        $packageUseLog = new PackageUseLog();

        $data = $storeModel->where($where)->limit($start, $limit)  ->order('create_time','desc')->select()->toArray();
        $store_id = array_column($data, 'store_id');
        $packageUseLogList = $packageUseLog->where('store_id', 'in', $store_id)->group('store_id')
            ->field('store_id,count(id) as count')
            ->select()->toArray();
        $packageUseLogListById = [];
        if ($packageUseLogList) {
            $packageUseLogListById = array_column($packageUseLogList, 'store_id');
        }
        $staff  = new StaffRole();
        $QRcode = new QRcode();
        foreach ($data as $key => $value) {
            if (array_key_exists($value['id'], $packageUseLogListById)) {
                $data[$key]['package_use_count'] = $packageUseLogListById[$value['store_id']]['count'];
            }else{
                $data[$key]['package_use_count'] = 0;
            }
            $data[$key]['user_count'] = $staff->where(['store_id'=> $value['id']])->count();
            $url = getProtocol() . $_SERVER["HTTP_HOST"].'/H5/index.html?store_id='.$value['id'].'#/pages/storePaymentCode/storePaymentCode';

            $imageString = $QRcode->png($url, './uploads/store/'.$value['id'].'.png', "2", 4, 1)->entry();
            $data[$key]['qr_code']  =$imageString;
        }
        $count = $storeModel->where($where)->count();
        return success('门店列表', ['list' => $data, 'count' => $count]);

    }

    public function myStaff(Request $request)
    {
        $param = $request->param();
        if (isset($param['store_id']) && !empty($param['store_id'])) {
            $where['store_id'] = $param['store_id'];
        } else {
            $where['store_id'] = $request->staff_account['store_id'];
        }


        $staffRoleModel = new StaffRole();
        $staffRoleArray = $staffRoleModel->where($where)->select()->toArray();
        $staffId = array_column($staffRoleArray, 'staff_id');
        $staffById = array_column($staffRoleArray, null, 'staff_id');
        $staffModel = new Staff();
        if (isset($param['account']) && !empty($param['account'])) {
            $staffAccount = $staffModel->where('id', 'in', $staffId)->where('phone', $param['account'])
                ->whereOr('name', $param['account'])->where(['status' => 1])
                ->field('id,phone,name,create_time,real_name')
                ->select()->toArray();
        } else {
            $staffAccount = $staffModel->where('id', 'in', $staffId)->where(['status' => 1])
                ->field('id,phone,name,create_time,real_name')
                ->select()->toArray();
        }
        $staffAccountById = array_column($staffAccount, null, 'id');
        $staff_id = array_column($staffAccount, 'staff_id');
        $packageUseLog = new PackageUseLog();
        $packageUseLogList = $packageUseLog->where('staff_id', 'in', $staff_id)->group('staff_id')
            ->field('staff_id,count(id) as count')
            ->select()->toArray();
        // 订单金额
        $amountLog = new AmountLog();
        $amountList = $amountLog->where('staff_id', 'in', $staff_id)
            ->group('staff_id')
            ->field('staff_id,sum(amount) as amount')
            ->select()->toArray();
        $amountListByStaffId = [];
        if ($amountList) {
            $amountListByStaffId = array_column($amountList, 'staff_id');
        }
        $packageUseLogListById = [];
        if ($packageUseLogList) {
            $packageUseLogListById = array_column($packageUseLogList, 'staff_id');
        }

        // 订单数量
        $orderCount = $amountLog->where('staff_id', 'in', $staff_id)
            ->where('operate_type', 'in', [2, 3])
            ->group('staff_id')
            ->field('staff_id,count(id) as count')
            ->select()->toArray();
        $orderCountById = [];
        if ($orderCount) {
            $orderCountById = array_column($orderCountById, 'staff_id');
        }

        foreach ($staffAccount as $key => $value) {
            if (isset($staffAccountById[$staffById[$value['id']]['pid']])) {
                $staffAccount[$key]['parent_name'] = $staffAccountById[$staffById[$value['id']]['pid']]['name'];
                $staffAccount[$key]['parent_phone'] = $staffAccountById[$staffById[$value['id']]['pid']]['phone'];
            } else {
                $staffAccount[$key]['parent_name'] = '';
                $staffAccount[$key]['parent_phone'] = '';
            }
            if (array_key_exists($value['id'], $packageUseLogListById)) {
                $staffAccount[$key]['package_use_count'] = $packageUseLogListById[$value['id']]['count'];
            }else{
                $staffAccount[$key]['package_use_count'] = 0;
            }
            if (array_key_exists($value['id'], $amountListByStaffId)) {
                $staffAccount[$key]['amount'] = $amountListByStaffId[$value['id']]['amount'];
            }else{
                $staffAccount[$key]['amount'] = 0;
            }
            if (array_key_exists($value['id'], $orderCountById)) {
                $staffAccount[$key]['order_count'] = $orderCountById[$value['id']]['count'];
            }else{
                $staffAccount[$key]['order_count'] =0;
            }
        }
        return success('员工列表', ['list' => $staffAccount, 'count' => count($staffAccount)]);
    }

    public function delStaff(Request $request)
    {
        $param = $request->param();
        $staffAccountModel = new Staff();
        $staffAccountModel->where(['id' => $param['id']])->update(['status' => 3]);
        return success('操作成功');
    }

    public function addStaff(Request $request)
    {
        $param = $request->param();
        $staffAccountModel = new Staff();
        $staffAccount = $staffAccountModel->where(['phone' => $param['phone']])->find();
        if (empty($staffAccount)) {
            $salt = createNonceStr(4);
            $data = [
                //'store_id' => $param['store_id'],
                'name' => $param['name'],
                'real_name' => $param['real_name'],
                'password' => md5(md5($param['password']) . $salt),
                'salt' => $salt,
                'create_time' => time(),
                'phone' => $param['phone'],
            ];
            $staffAccountModel->insert($data);
            $staffId = $staffAccountModel->getLastInsID();
        } else {
            $staffId = $staffAccount['id'];
        }
        $staffRoleData = [
            'staff_id' => $staffId,
            'role_id' => $param['role_id'],
            'store_id' => $param['store_id'],
            'pid' => $param['pid'],
            'create_time' => time(),
        ];
        $staffRoleModel = new StaffRole();
        $staffRoleModel->insert($staffRoleData);
        return success('添加成功');
    }

    /**
     * 修改密码
     */
    public function upPassword(Request $request)
    {
        $param = $request->param();
        $staffAccountModel = new Staff();
        $salt = createNonceStr(4);
        $staffAccountModel->where(['id' => $param['id']])
            ->update(['password' => md5(md5($param['password']) . $salt), 'salt' => $salt]);
        $jwt = new JwtService();
        $token = $jwt->getMerchantToken($param['id'], $request->staff_account['role_id'], $request->staff_account['store_id'], 30);  //获取token
        $tokenConfig = ['uid' => $param['id'], 'token' => $token, 'create_time' => time(),
            'effective_time' => time() + 60 * 60 * 24 * 30, 'login_ip' => $request->ip(), 'type' => 2];  //token配置信息  //token配置信息
        $tokenModel = new UserToken();
        $tokenModel->insert($tokenConfig);
        return success('操作成功');
    }
    public function  addPrinter(Request $request){
        $param = $request->param();
        $time = time();
        $feieString = $param['fe_user'].$param['fe_userkey'].$time;
        $data['fe_user'] = $param['fe_user'];
        $data['fe_userkey'] = $param['fe_userkey'];
        $data['fe_key'] = $param['fe_key'];
        $data['fe_sn'] = $param['fe_sn'];
        $data['store_id'] = $param['store_id'];
        $data['name'] = $param['name'];
        $data['create_time'] = time();
        try {
            $msgInfo = array(
                'user' => $param['fe_user'],
                'stime' => $time,
                'sig' => sha1($feieString),
                'apiname' => 'Open_printerAddlist',
                'printerContent' => $param['fe_sn'] . '#' . $param['fe_key'],
            );
            $dataString = curlPost('https://api.feieyun.cn/Api/Open/', $msgInfo);
            $printer = new Printer();
            $printer->insert($data);
            /*    if ($dataArray['ret'] == 0) {
                    if (empty($dataArray['no'])){

                    }else{
                        return error($dataArray['no'][0]);
                    }
                }*/
        } catch (Exception $exception) {
            return adminError($exception->getMessage());
        }
        return adminSuccess('添加成功');
    }
    public function  editPrinter(Request $request){
        $param = $request->param();
        $time = time();
        $feieString = $param['fe_user'].$param['fe_userkey'].$time;
        $data['fe_user'] = $param['fe_user'];
        $data['fe_userkey'] = $param['fe_userkey'];
        $data['fe_key'] = $param['fe_key'];
        $data['fe_sn'] = $param['fe_sn'];
        $data['store_id'] = $param['store_id'];
        $data['name'] = $param['name'];
        $data['create_time'] = time();
        try {
            $msgInfo = array(
                'user' => $param['fe_user'],
                'stime' => $time,
                'sig' => sha1($feieString),
                'apiname' => 'Open_printerAddlist',
                'printerContent' => $param['fe_sn'] . '#' . $param['fe_key'],
            );
            $dataString = curlPost('https://api.feieyun.cn/Api/Open/', $msgInfo);
            $printer = new Printer();
            $printer->where(['id' => $param['id']])->update($data);
            /*    if ($dataArray['ret'] == 0) {
                    if (empty($dataArray['no'])){

                    }else{
                        return error($dataArray['no'][0]);
                    }
                }*/
        } catch (Exception $exception) {
            return adminError($exception->getMessage());
        }
        return adminSuccess('添加成功');
    }
    public  function  printerList(Request $request){
        $printer = new Printer();
        if ($request->staff_account['store_id']){
            $list = $printer ->where(['store_id' => $request->staff_account['store_id']])->select()->toArray();
            $count = $printer->where(['store_id' => $request->staff_account['store_id']])->count();
        }else{
            $list = $printer->select()->toArray();
            $count = $printer->count();
        }
        if ($list){
            $store_id = array_column($list,'store_id');
            $StoreModel =  new \app\merchant\model\Store();
            $storeList = $StoreModel->where('id','in',$store_id)->select()->toArray();
            $storeListByid = array_column($storeList,null,'id');
            foreach ($list as  $key => $value){
                if (array_key_exists($value['store_id'],$storeListByid)){
                    $list[$key]['store_name'] = $storeListByid[$value['store_id']]['name'];
                }else{
                    $list[$key]['store_name'] = '';
                }
            }
        }
        return adminSuccess('打印机列表',['list' => $list,'count' => $count]);
    }
    public function printing(Request $request){
        $param = $request->param();
        $messagePayType = '';
        if ($param['type'] == 1){
            $packageOrderModel = new PackageOrder();
            $packageOrderInfo = $packageOrderModel->where(['id' => $param['id']])->find();
            $packageModel =  new \app\merchant\model\Package();
            $packageInfo = $packageModel->where(['id' => $packageOrderInfo['package_id']])->find();
            $info['name'] = $packageInfo['name'];
            $info['price'] = $packageOrderInfo['price'];
            $info['number'] = 1;
            $info['sn_order'] = $packageOrderInfo['order_sn'];

            switch ($packageOrderInfo['pay_type']) {
                case 1:
                    $messagePayType = '余额';
                    break;
                case 2:
                    $messagePayType = '微信';
                    break;
                case 3:
                    $messagePayType = '微信'; // 门店扫码
                    break;
                case 4:
                    $messagePayType = '支付宝';
                    break;
                case 5:
                    $messagePayType = '现金';
                    break;
                case 6:
                    $messagePayType = '刷卡';
                    break;
                case 7:
                    $messagePayType = '微信';
                    break;
                case 8:
                    $messagePayType = '支付宝';
                    break;
            }
        }else{
            $goodsOrderModel  = new GoodsOrder();
            $goodsOrderInfo = $goodsOrderModel->where(['id' => $param['id']])->find();
            $info['name'] = $goodsOrderInfo['goods_name'];
            $info['price'] = $goodsOrderInfo['reality_amount'];
            $info['number'] = $goodsOrderInfo['number'];
            $info['number'] = 1;
            $info['sn_order'] = $goodsOrderInfo['sn_order'];
            switch ($goodsOrderInfo['pay_way']) {
                case 1:
                    $messagePayType = '余额';
                    break;
                case 2:
                    $messagePayType = '微信';
                    break;
                case 3:
                    $messagePayType = '微信'; // 门店扫码
                    break;
                case 4:
                    $messagePayType = '支付宝';
                    break;
                case 5:
                    $messagePayType = '现金';
                    break;
                case 6:
                    $messagePayType = '刷卡';
                    break;
                case 7:
                    $messagePayType = '微信';
                    break;
                case 8:
                    $messagePayType = '支付宝';
                    break;
            }
        }

        $content = '<CB>购买商品</CB><BR>';
        $content .= '--------------------------------<BR>';
        $content .= '商品名称: '.$info['name'].'<BR>';
        $content .= '购买数量: '.$info['number'].'<BR>';
        $content .= '支付金额: '.$info['price'].'元<BR>';
        $content .= '支付方式: '.$messagePayType.'<BR>';
        $content .= '--------------------------------<BR>';
        $content .= '购买时间:'. date('Y-m-d').'<BR>';
        $content .= '合计：'.$info['price'].'<BR>';
        $content .= '<QR>'.getProtocol().$_SERVER["HTTP_HOST"].'/H5/index.html'.'</QR>';

        $printer = new Printer();
        $printerInfo =  $printer->where(['id'=> $param['printer_id']])->find();
        $time = time();
        $msgInfo = array(
            'user'=>$printerInfo['fe_user'],
            'stime'=>$time,
            'sn'=>$printerInfo['fe_sn'],
            'sig'=>sha1($printerInfo['fe_user'].$printerInfo['fe_userkey'].$time),
            'apiname'=>'Open_printMsg',
            'content'=>$content,
            'times' => 1,
        );
        $data  = curlPost('https://api.feieyun.cn/Api/Open/',$msgInfo);
        $dataArray = (array)json_decode($data, true);
        if ($dataArray['ret'] == 0){
            return adminSuccess('打印成功');
        }
        return adminError('失败');
    }

    public function delPrinting(Request $request){
        $param = $request->param();
        $printer = new Printer();
         $printer->where(['id'=> $param['printer_id']])->delete();
        return adminSuccess('成功');
    }





}